package com.alisls.demo.sso.crm.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 发送Http的工具
 *
 * @author Ke Wang
 */
public class HttpUtil {

    /**
     * 发送Post请求
     * @param uri 请求地址
     * @param paramMap 请求参数
     * @return 结果
     */
    public static String sendPost(String uri, Map<String, Object> paramMap) {
        return sendPost(uri, null, paramMap);
    }

    /**
     * 发送Post请求
     *
     * @param uri      资源路径
     * @param sessionId 会话标识
     * @param paramMap 参数
     * @return 结果
     */
    public static String sendPost(String uri, String sessionId, Map<String, Object> paramMap) {
        String result = "";
        try {
            URL url = new URL(uri);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");

            // 设置会话标识
            if (sessionId != null) {
                httpURLConnection.addRequestProperty("Cookie", "JSESSIONID=" + sessionId);
            }

            // 需要输出参数，所以要设置doOutput为true
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            if (paramMap != null) {
                // 拼接参数
                StringBuffer params = new StringBuffer();
                Set<Map.Entry<String, Object>> entries = paramMap.entrySet();
                entries.forEach(e -> params.append("&").append(e.getKey()).append("=").append(e.getValue()));
                String paramStr = params.toString();
                if (paramStr.startsWith("&")) {
                    paramStr = paramStr.substring(1);
                }
                // 写出参数
                httpURLConnection.getOutputStream().write(paramStr.getBytes(StandardCharsets.UTF_8));
            }

            // 连接服务器
            httpURLConnection.connect();

            StringBuilder resultBuffer = new StringBuilder();
            InputStream inputStream = httpURLConnection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            BufferedReader buff = new BufferedReader(inputStreamReader);
            String line;
            while ((line = buff.readLine()) != null) {
                resultBuffer.append(line);
            }
            inputStream.close();
            inputStreamReader.close();

            result = resultBuffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    public static void main(String[] args) {
        Map<String, Object> params = new HashMap<>();
        params.put("token", "123");
        sendPost("http://www.sso.com:8443/token/check", params);
    }

}
